package com.dundun.common.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSON;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.dundun.domain.User;
import java.util.HashMap;
import java.util.Map;

import static com.dundun.common.constants.DundunConstant.DUNDUN;
import static com.dundun.common.constants.DundunConstant.USER_PAYLOAD;

/**
 * @author eterlar
 */
public class DundunJwtUtil {

    public static String getJwt(User user) {
        Map<String,Object> payload = new HashMap<>();
        DateTime now = DateTime.now();
        DateTime newTime = now.offsetNew(DateField.MINUTE, 10);
        payload.put(USER_PAYLOAD,user);
        //签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, newTime);
        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        return JWTUtil.createToken(payload, DUNDUN.getBytes());
    }

    public static boolean verifyToken(String token) {
        System.out.println(token);
        try {
            token = token.substring(4);
            final JWT jwt = JWTUtil.parseToken(token);
            boolean verifyKey = jwt.setKey(DUNDUN.getBytes()).verify();
            boolean verifyTime = jwt.validate(0);
            if (verifyKey == true && verifyTime == true){
                return true;
            }else {
                return false;
            }
        }catch (Exception e){
            return false;
        }




    }

}
